package com.toutou.kotlin.vm

import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.lifecycle.viewModelScope
import com.toutou.base.util.SingleLiveEvent
import com.toutou.base.viewmodel.BaseViewModel
import com.toutou.base.been.ChatModule
import com.toutou.base.util.ToastUtil
import com.toutou.kotlin.apiService
import kotlinx.coroutines.launch


class MainVM : BaseViewModel() {
    val authSuccess = ObservableBoolean(false)
    val inputMessage = ObservableField<String>()

    init {
        authLLM()
    }

    fun authLLM() {
        viewModelScope.launch {
            runCatching {
                apiService.auth()
            }.onSuccess {
                authSuccess.set(it.authenticated)
            }.onFailure {
                authSuccess.set(false)
                it.printStackTrace()
            }
        }
    }


    val sendRequest = SingleLiveEvent<ChatModule>()
    val sendResult = SingleLiveEvent<ChatModule>()
    fun sendMessageApi() {
        viewModelScope.launch {
            runCatching {
                sendRequest.postValue(
                    ChatModule(
                        isMe = true,
                        message = inputMessage.get() ?: ""
                    )
                )
                apiService.sendMessage("fzy", ChatModule(message = inputMessage.get() ?: ""))
            }.onSuccess {
                sendResult.postValue(it)
            }.onFailure {
                it.printStackTrace()
                ToastUtil.showToast(it.message)
            }
        }
    }
}
